package zuo.from0516.other.day07;

import zuo.from0516.other.day06.TreeNode;

/**
 * Q110：平衡二叉树：
 * 给定一个二叉树，判断它是否是平衡二叉树
 *
 *
 */
public class Code02_BalancedBinaryTree {
    public static class Info{
        public int length;
        public boolean isBalance;

        public Info(int length, boolean isBalance) {
            this.length = length;
            this.isBalance = isBalance;
        }
    }
    public boolean isBalanced(TreeNode root) {
       return getInfo(root).isBalance;
    }

    public Info getInfo(TreeNode root){
        if (root == null){
            return new Info(0, true);
        }
        Info leftInfo = getInfo(root.left);
        Info rightInfo = getInfo(root.right);
        int length = Math.max(leftInfo.length, rightInfo.length) + 1;
        boolean isBalance = leftInfo.isBalance && rightInfo.isBalance && Math.abs(leftInfo.length  - rightInfo.length) < 2;
        return new Info(length, isBalance);
    }


}
